# Create your models here.
from django.db import models
from django.db.models import signals
import subprocess

class User(models.Model):
    name = models.CharField(max_length=255, unique=True)
    password = models.CharField(max_length=255)
    
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __unicode__(self):
        return self.name

passwd_file = '/home/jay/proxy/auth-password'
passwd_file2 = '/home/jay/proxy/auth-password2'

class UpdateUserFail(Exception):
    def __init__(self, user, passwd):
        self.user = user
        self.passwd = passwd
    def __str__(self):
        return 'Update User (%s: %s) Fails.'%(self.user, self.passwd)
        
def count_lines(fn):
    return len(open(fn).read().split('\n')) -1
    
def update_user(sender, instance, **kwargs):
    u = instance
  
    p = subprocess.Popen('cp %s %s'%(passwd_file, passwd_file2) , shell=True)
    n = count_lines(passwd_file)
  
    command = 'htpasswd -b %s %s %s'%(passwd_file, u.name, u.password)
    p = subprocess.Popen(command, shell=True)
  
    n2 = count_lines(passwd_file)
    if n2 < n:
        p = subprocess.Popen('cp %s %s'%(passwd_file2, passwd_file) , shell=True)
        raise UpdateUserFail(u.name, u.password)    
signals.pre_save.connect(update_user, sender=User)

def del_user(sender, instance, **kwargs):
    u = instance
    command = 'htpasswd -D %s %s'%(passwd_file, u.name)
    p = subprocess.Popen(command, shell=True)
signals.post_delete.connect(del_user, sender=User)

